package net.loyin.app.ctrl.admin;

import com.jfinal.plugin.ehcache.CacheKit;
import net.loyin.ext.annotation.ControllerBind;
import net.loyin.ext.annotation.CtrlMethod;
import net.loyin.app.Constant;
import net.loyin.app.model.Link;
import org.apache.commons.lang.StringUtils;

/**
 *友情链接
 * Created by loyin on 16/1/12.
 */
@ControllerBind(route = "/admin/link")
public class LinkCtrl extends AdminBaseCtrl {

    public void index(){
        int pageNumber=this.getParaToInt("pageNumber",1);
        int pageSize=this.getParaToInt("pageSize",20);
        StringBuffer sql=new StringBuffer("from ");
        sql.append(Link.tableName);
        this.setAttr("page",Link.dao.paginate(pageNumber,pageSize,"select * ",sql.toString()));
    }
    public void add(){
        String id=this.getPara(0);
        if(StringUtils.isNotBlank(id)){
            this.setAttr("po",Link.dao.findById(id));
        }
    }
    @CtrlMethod(isAjax = true)
    public void save(){
        Link entity=this.getModel(Link.class);
        if(entity!=null){
            String id=entity.getId();
            if(StringUtils.isEmpty(id)) {
                entity.save();
            }else{
                entity.update();
            }
            CacheKit.remove(Constant.CACHE_KEY_1DAY,"link");
            this.renderJsonMsg(JSON_RESULT_SUCCESS,"保存成功!");
        }else{
            this.renderJsonMsg(JSON_RESULT_ERROR,"保存失败!");
        }
    }
    @CtrlMethod(isAjax = true)
    public void del(){
        String id=this.getPara(0);
        try {
            if (StringUtils.isNotBlank(id)) {
                Link.dao.deleteById(id);
                this.renderJsonMsg(JSON_RESULT_SUCCESS,"删除成功!");
            } else {
                this.renderJsonMsg(JSON_RESULT_WARNNING, "缺少参数!");
            }
        }catch (Exception e){
            logger.error("删除异常",e);
            this.renderJsonMsg(JSON_RESULT_ERROR, "删除异常,可能存在引用,请先删除对应的数据!");
        }
    }
}
